package com.zqsoft.dao;

import com.zqsoft.bean.CropBean;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

public class CropDAO {

    public static List<CropBean> getAllCrop() {
        List<CropBean> allCrops = new ArrayList<>();
        File directory = new File("resources/crops");

        // 过滤出子目录
        String[] cropDirs = directory.list((File dir, String name) -> new File(dir, name).isDirectory());

        if (cropDirs != null) {
            for (String cropDirName : cropDirs) {
                File cronFile = new File(directory, cropDirName + "/cron.properties");
                if (cronFile.exists() && cronFile.isFile()) { // 确保文件存在且为文件
                    Properties properties = new Properties();
                    try (FileReader fr = new FileReader(cronFile)) { // 使用 try-with-resources 自动关闭 FileReader
                        properties.load(fr);
                        CropBean crop = new CropBean();
                        crop.setCropId(Integer.parseInt(properties.getProperty("ITEM_ID")));
                        crop.setCropName(properties.getProperty("ITEM_NAME"));
                        crop.setSeedPic("resources/crops/" + cropDirName + "/" + properties.getProperty("ITEM_SEED_PIC"));
                        crop.setStage(Integer.parseInt(properties.getProperty("ITEM_STAGE")));
                        crop.setSellPrice(Integer.parseInt(properties.getProperty("ITEM_SELL_MONEY"))); // 修正了属性名
                        crop.setPrice(Integer.parseInt(properties.getProperty("ITEM_PRICE")));
                        crop.setBuyLevel(Integer.parseInt(properties.getProperty("ITEM_NEED_LEVEL")));

                        List<String> allStagePic = new ArrayList<>();
                        List<Integer> allStageTime = new ArrayList<>();
                        int stage = Integer.parseInt(properties.getProperty("ITEM_STAGE"));
                        for (int i = 1; i <= stage; i++) {
                            allStagePic.add("resources/crops/" + cropDirName + "/" + properties.getProperty("ITEM_STAGE_" + i));
                            allStageTime.add(Integer.parseInt(properties.getProperty("ITEM_STAGE_NEXT_TIME_" + i)));
                        }
                        crop.setAllStagePic(allStagePic);
                        crop.setAllStageTime(allStageTime);

                        allCrops.add(crop);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }

        return allCrops;
    }
}